<template>
  <div class="app-container page-container">
    <div class="search-area">
      <el-select v-model="pid" placeholder="请选择大机" size="small" clearable @change="fetchData(1)">
        <el-option
          v-for="item in machineOptions"
          :key="item.id"
          :label="item.deviceName"
          :value="item.id"
        />
      </el-select>
      <el-input v-model="deviceName" placeholder="请输入统计对象名称" size="small" clearable class="search-value" />
      <el-button size="small" style="margin-left: 12px" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button type="primary" size="small" style="margin-left: 12px" @click="handleDownload">导出</el-button>
    </div>
    <div class="table-container">
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        border
        height="100%"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        :header-cell-style="{
          background:'#6c89e7',color:'#000000'
        }"
      >
        <!--        <el-table-column-->
        <!--          type="selection"-->
        <!--          width="55"-->
        <!--        />-->
        <el-table-column label="起重机号" prop="craneName" />
        <el-table-column label="名称" prop="deviceName" />
        <el-table-column label="统计类型" prop="statisticalType" />
        <el-table-column label="统计值" prop="statisticalValue" />
        <el-table-column label="理论寿命" prop="theoreticalLifespan" />
        <el-table-column label="一级预警" prop="firstLevelWarning" :formatter="(row) => `${row.firstLevelWarning * 100}%`" />
        <el-table-column label="二级预警" prop="secondLevelWarning" :formatter="(row) => `${row.secondLevelWarning * 100}%`" />
        <el-table-column
          v-if="token"
          fixed="right"
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleModify(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleReplace(scope.row)"
            >
              更换
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        :current-page="pageNumber"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <DeviceDialog :title="title" :visible.sync="showDialog" :device-info="deviceInfo" @onSuccess="fetchData()" />
  </div>
</template>

<script>
import {
  downloadDeviceEarlyWarningRecords,
  queryDeviceEarlyWarningList, queryDeviceList
} from '../../api/device'
import DeviceDialog from '@/components/DeviceDialog'
import * as dayjs from 'dayjs'
import { mapGetters } from 'vuex'

export default {
  name: 'EarlyWarning',
  components: { DeviceDialog },
  data() {
    return {
      value: '',
      list: null,
      listLoading: true,
      currentPage4: 4,
      multipleSelection: [],
      pageSize: 10,
      pageNumber: 1,
      total: 0,
      deviceInfo: {},
      title: '更换设备',
      showDialog: false,
      pid: undefined,
      machineOptions: [],
      deviceName: '',
      timer: null
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  watch: {
    showDialog: {
      handler(val) {
        if (val) {
          this.handleClearInterval()
        } else {
          this.handleInterval()
        }
      }
    }
  },
  mounted() {
    this.fetchData()
    this.getMachineList()
    this.handleInterval()
  },
  beforeDestroy() {
    this.handleClearInterval()
  },
  methods: {
    handleSearch() {
      this.fetchData(1)
    },
    handleInterval() {
      if (this.timer) {
        this.handleClearInterval()
      }
      this.timer = setInterval(() => {
        // 15 分钟刷新一次页面
        this.fetchData()
      }, 1000 * 60 * 15)
    },
    handleClearInterval() {
      clearInterval(this.timer)
      this.timer = null
    },
    fetchData(page) {
      this.listLoading = true
      queryDeviceEarlyWarningList({
        pageNumber: page || this.pageNumber,
        pageSize: this.pageSize,
        deviceName: this.deviceName,
        firstLevelTreeId: this.pid
      }).then(({ data, success }) => {
        if (success) {
          this.list = data?.data || []
          this.total = data?.total || 0
        }
      }).finally(() => { this.listLoading = false })
    },
    getMachineList() {
      queryDeviceList().then(({ data, success }) => {
        if (success) {
          this.machineOptions = data || []
        }
      })
    },
    tableRowClassName({ row }) {
      if (row.status === 1) {
        return 'warning-row'
      } else if (row.status === 2) {
        return 'error-row'
      }
      return ''
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNumber = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.fetchData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDownload() {
      downloadDeviceEarlyWarningRecords({
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        firstLevelTreeId: this.pid,
        deviceName: this.deviceName
      }).then(resp => {
        if (resp) {
          const a = document.createElement('a')
          const url = window.URL.createObjectURL(new Blob([resp]))
          // 创建url对象
          a.href = url
          a.download = `预警记录-${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
          a.click()
          // 释放url对象
          window.URL.revokeObjectURL(url)
        }
      })
    },
    handleReplace(row) {
      this.title = '更换设备'
      this.deviceInfo = { ...row, title: '更换设备' }
      this.showDialog = true
    },
    handleModify(row) {
      this.title = '修改设备'
      this.deviceInfo = { ...row, title: '修改设备' }
      this.showDialog = true
    }
  }
}
</script>

<style>
.el-table .warning-row {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.el-table .error-row {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>

<style lang="scss" scoped>
.search-area {
  margin-bottom: 16px;
  text-align: right;
  .search-value{
    width: 200px;
    margin-left: 12px;
  }
}
.table-container {
  height: calc(100vh - 215px);
}
.pagination-container {
  margin-top: 10px;
}
</style>
